package com.music.player;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.lang.reflect.Method;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Set;
import com.music.list.AllMusicActivity;
import com.music.lrc.LrcProcessor;
import com.music.main.MainActivity;
import com.music.mp3.Lrc;
import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.net.Uri;
import android.os.Handler;
import android.os.IBinder;
import android.util.Log;

public class PlayerService extends Service{
	//播放器对象
	public static MediaPlayer player=null;
	//代表是否正在播放
	public static boolean isplaying=false;
	//代表是否处于停止状态
	public static boolean stop=false;
	//各种操作代号
	public static final int PLAY=0;  //播放
	public static final int PAUSE=1; //暂停
	public static final int STOP=2;  //停止
	public static final int LAST=3;  //上一曲
	public static final int NEXT=4;  //下一曲
	public static final int MOVE=5;  //拖动滚动条播放
	public static final int CREATE=-1; //创建播放器对象
	//歌词对象
	Lrc lrc=null;
	 //这是播放时间的分和秒
    int min=0,currentMin=0;
    int sec=0,currentSec=0;
    //更新时间与进度条线程
    Handler handler=new Handler();
    //这是从QueueTime里面得到时间
    long nextTimeMill=0;
    //歌词内容
    String lrcContent=null;
    //用于存储lrc歌词的时间
    public static Queue<Long> timeQueue=null;
	//用于存储lrc歌词的时间和内容
    public static LinkedHashMap<Long,String> map=null;
    //系统开始播放时间
    long begin=0;
    //当前播放了多少时间
    long mv=0;
    //集合中存放的键
    Set<Long> s=null;
    //判断是否按下暂停
    boolean putpause=true;
    //暂停时系统时间
    long startime=0;
    //播放时系统喜欢
    long endtime=0;
    //暂停了多少时间
    long pausetime=0;
    //播放模式
    public static int pattern=0;
    //是否显示歌词
    public static int look=0;
	@Override
	public IBinder onBind(Intent arg0) {
		// TODO Auto-generated method stub
		return null;
	}
	//启动Service进行的操作
	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		// TODO Auto-generated method stub
		//获得操作类型
		int doPlayer=intent.getIntExtra("doPlayer", 0);
		if(doPlayer==CREATE){
			createPlayer();
		}else if(doPlayer==PLAY){
			play();
		}else if(doPlayer==PAUSE){
			pauseMp3();
		}else if(doPlayer==STOP){
			stopMp3();
		}else if(doPlayer==NEXT){
			changeMp3();
		}else if(doPlayer==LAST){
			changeMp3();
		}else if(doPlayer==MOVE){
			move();
		}
		return super.onStartCommand(intent, flags, startId);
	}
	//播放操作
	public void play(){
		if(player!=null){
			if(stop){
				createPlayer();
				stop=false;
				isplaying=true;
			}else{
				//获得暂停了多少时间
				if(lrc!=null){
					if(!putpause){
						endtime=System.currentTimeMillis();
						pausetime+=endtime-startime;
						handler.post(updateSeekBar);
						putpause=true;
					}
				}
				player.start();
				isplaying=true;
			}	
		}
	}
	//暂停操作
	public void pauseMp3(){
		if(player!=null){
			if(lrc!=null){
				//获得按下暂停时的系统时间
				if(putpause){
					startime=System.currentTimeMillis();
					handler.removeCallbacks(updateSeekBar);
					putpause=false;
				}
			}
				player.pause();
				isplaying=false;
		}
	}
	//停止操作
	public void stopMp3(){
		if(player!=null){
			if(!stop){
				 Mp3PlayerActivity.time.setText(0+""+0+":"+0+""+0);
				 timeQueue=null;
				 mv=0;
				 pausetime=0;
				 Mp3PlayerActivity.movetime=0;
				 handler.removeCallbacks(updateSeekBar);
				 Mp3PlayerActivity.bar.setProgress(0);
				 Mp3PlayerActivity.lr.setText("");
				 player.stop();
			     player.release();
			     isplaying=false;
			     stop=true;
			}	
		}
	}
	//创建播放歌曲
	public void createPlayer(){
		player=MediaPlayer.create(this,Uri.parse("file://"+Mp3PlayerActivity.path));
		if(look==0){
			lrc=getLrc();
			if(lrc!=null){
				readLrc();
			}else{
				Mp3PlayerActivity.lr.setText("未搜索到歌词！");
			}
		}else if(look==1){
			Mp3PlayerActivity.lr.setText("");
		}
		Mp3PlayerActivity.name.setText("歌曲："+Mp3PlayerActivity.m.getMp3_name());
		//为mediaPlayer设置是否播放完成的监听器
		player.setOnCompletionListener(new CompletionListener());
		// 设置默认进度条的最大值				
		Mp3PlayerActivity.bar.setMax(player.getDuration());  
		handler.post(updateSeekBar);
		player.start();
		begin=System.currentTimeMillis();
		 //启动handler
		isplaying=true;
		stop=false;
	}
	//歌曲切换时操作
	public void changeMp3(){
		if(stop){
			
			createPlayer();
		}else{
		
			stopMp3();
			createPlayer();
		}
	}
	Runnable updateSeekBar=new Runnable(){
		public void run() {
			 		mv=System.currentTimeMillis()-begin+Mp3PlayerActivity.movetime-pausetime;
			        int CurrentPosition = 0;// 设置默认进度条当前位置  
			        //得到mediaPlayer的当前播放位置
		            CurrentPosition = player.getCurrentPosition();
		            //设置进度条的当前位置
		            Mp3PlayerActivity.bar.setProgress(CurrentPosition);  
		            min=(player.getDuration()/1000)/60;
		            sec=(player.getDuration()/1000)%60;
		            currentMin=(CurrentPosition/1000)/60;
		            currentSec=(CurrentPosition/1000)%60;
		            //为时间Text设置时间
		            if(currentSec<10){
		            	Mp3PlayerActivity.time.setText(0+""+currentMin+":"+"0"+currentSec);
		            }else{
		            	Mp3PlayerActivity.time.setText(0+""+currentMin+":"+currentSec);
		            }
		            //设置歌词
		         if(look==0){
		        	 if(lrc!=null){
			            	if(mv>=nextTimeMill){
			            		
			            		if(timeQueue.peek()!=null){
			            			Mp3PlayerActivity.lr.setText(lrcContent);
			            			
			            			nextTimeMill=timeQueue.poll();
				            		lrcContent=map.get(nextTimeMill);					    
							      }else{
							    	
							    	  lrcContent="";
							    	  Mp3PlayerActivity.lr.setText(lrcContent);
							      }
			            		
			            	}
				        }
		         }
		            handler.postDelayed(updateSeekBar,10);  
		}
	};
	//监听是否播放完成
    class CompletionListener implements OnCompletionListener{
		@Override
		public void onCompletion(MediaPlayer mp) {
			// TODO Auto-generated method stub
			Mp3PlayerActivity.time.setText(0+""+0+":"+0+""+0);
			timeQueue=null;
			mv=0;
			pausetime=0;
			Mp3PlayerActivity.movetime=0;
			handler.removeCallbacks(updateSeekBar);
			Mp3PlayerActivity.bar.setProgress(0);
			Mp3PlayerActivity.lr.setText("");
			if(pattern==0){
				createPlayer();
			}else if(pattern==1){
				if(Mp3PlayerActivity.index==AllMusicActivity.mp3list.size()-1){
					Mp3PlayerActivity.index=0;
					Mp3PlayerActivity.m=AllMusicActivity.mp3list.get(Mp3PlayerActivity.index);
					Mp3PlayerActivity.path=MainActivity.SDPath+"mp3/"+Mp3PlayerActivity.m.getMp3_name()+".mp3";
					createPlayer();
				}else{
					Mp3PlayerActivity.index=Mp3PlayerActivity.index+1;
					Log.i("index", Mp3PlayerActivity.index+"");
					Mp3PlayerActivity.m=AllMusicActivity.mp3list.get(Mp3PlayerActivity.index);
					Mp3PlayerActivity.path=MainActivity.SDPath+"mp3/"+Mp3PlayerActivity.m.getMp3_name()+".mp3";
					createPlayer();
				}
			}else if(pattern==2){
				int i=(int)(Math.random()*AllMusicActivity.mp3list.size());
				Mp3PlayerActivity.index=i;
				Mp3PlayerActivity.m=AllMusicActivity.mp3list.get(Mp3PlayerActivity.index);
				Mp3PlayerActivity.path=MainActivity.SDPath+"mp3/"+Mp3PlayerActivity.m.getMp3_name()+".mp3";
				createPlayer();
			}
			
		}
    	
    }
    //拖动滚动条时操作
    public void move(){
    	if(look==0){
    		if(lrc!=null){
        		mv=System.currentTimeMillis()-begin+Mp3PlayerActivity.movetime-pausetime;
//            	timeQueue=new LinkedList<Long>();
//            	for(Long l:s){
//            		if(l>=mv){
//            			timeQueue.offer(l);
//            		}
//            	}
        		readLrc();
            	nextTimeMill=timeQueue.poll();
        		lrcContent=map.get(nextTimeMill);
        		Mp3PlayerActivity.lr.setText(lrcContent);
            	player.seekTo((int)mv);
        	}else{
        		player.seekTo(Mp3PlayerActivity.i);
        	}
    	}else if(look==1){
    		player.seekTo(Mp3PlayerActivity.i);
    	}
    }
    public void readLrc(){
			map=lrc.getContent();
	    	timeQueue=new LinkedList<Long>();
	    	s=map.keySet();
	    	for(Long l:s){
	    		timeQueue.offer(l);
	    	}
	    	nextTimeMill=timeQueue.poll();
    		lrcContent=map.get(nextTimeMill);
    		Mp3PlayerActivity.lr.setText(lrcContent);
    }
    //获得Lrc文件对象
    public Lrc getLrc(){
    	String path=MainActivity.SDPath+"mp3/"+Mp3PlayerActivity.m.getMp3_name()+".lrc";
    	InputStream inputStream=null;
    	Lrc lrc_result=null;
		try {
			inputStream = new FileInputStream(path);
			LrcProcessor p=new LrcProcessor();
			lrc_result=p.process(inputStream);
		} catch (FileNotFoundException e){
			// TODO Auto-generated catch block
			return null;
		}
    	return lrc_result;
    }
}